﻿
using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Dto.SaveDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using SqlSugar;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Repository.Repositorys
{
    /// <summary>
    /// 旅行社组织机构用户映射表仓储层
    /// </summary>
    public class TasOrgUserMapRepository : SqlSugarRepository<TasOrgUserMapEntity, Guid>
    {
        private ISugarUnitOfWork _unitOfWork;
        public TasOrgUserMapRepository(ISugarUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<int> CreateRange(List<TasOrgUserMapEntity> list)
        {
            var result = await _unitOfWork.ModifyClient.Insertable(list).ExecuteCommandAsync();
            return result;
        }
        
        /// <summary>
        /// 通过角色Id获取权限所属的员工
        /// </summary>
        /// <param name="EmployeeIdList"></param>
        /// <returns></returns>
        public async Task<int> GetCountByOrgIdList(List<int> orgIdList)
        {
            var result = await _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity>()
                .Where(it => orgIdList.Contains(it.OrgId))
                .CountAsync();
            return result;
        }


        /// <summary>
        /// 批量禁用组织机构帐号
        /// </summary>
        public async Task<bool> BatchDisable(List<TasOrgUserPKSaveDto> list)
        {
            if (list == null || list.Count == 0)
            {
                return false;
            }
            var strWhere = "";
            var paramArr = new SugarParameter[list.Count*2];
            for (int i = 0; i < list.Count; i++)
            {
                var item = list[i];
                if (i == 0)
                {
                    strWhere += $"(UserId=@UserId{i} AND OrgId=@OrgId{i})";
                }
                else
                {
                    strWhere += $" or (UserId=@UserId{i} AND OrgId=@OrgId{i})";
                }
                paramArr[2 * i] = new SugarParameter($"@UserId{i}", item.UserId);
                paramArr[2 * i+1] = new SugarParameter($"@OrgId{i}", item.OrgId);
            }
            var strSql = $"UPDATE tas_org_user_map SET IsDisabled=1 WHERE {strWhere}";
            var result = _unitOfWork.ModifyClient.Ado.ExecuteCommand(strSql, paramArr) > 0;
            return result;
        }

        /// <summary>
        /// 批量启用组织机构帐号
        /// </summary>
        public async Task<bool> BatchEnable(List<TasOrgUserPKSaveDto> list)
        {
            try
            {
                if (list == null || list.Count == 0)
                {
                    return false;
                }
                var strWhere = "";
                var paramArr = new SugarParameter[list.Count*2];
                for (int i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    if (i == 0)
                    {
                        strWhere += $"(UserId=@UserId{i} AND OrgId=@OrgId{i})";
                    }
                    else
                    {
                        strWhere += $" or (UserId=@UserId{i} AND OrgId=@OrgId{i})";
                    }
                    paramArr[2 * i] = new SugarParameter($"@UserId{i}", item.UserId);
                    paramArr[2 * i + 1] = new SugarParameter($"@OrgId{i}", item.OrgId);
                }
                var strSql = $"UPDATE tas_org_user_map SET IsDisabled=0 WHERE {strWhere}";
                var result = _unitOfWork.ModifyClient.Ado.ExecuteCommand(strSql, paramArr) > 0;
                return result;
            }
            catch(Exception ex)
            {
                
            }
            return false;
        }

        /// <summary>
        /// 删除组织机构帐号
        /// </summary>
        public async Task<bool> Delete(TasOrgUserMapEntity entity)
        {
            try
            {
                var result =await _unitOfWork.ModifyClient.Deleteable(entity).ExecuteCommandAsync() > 0;
                return result;
            }
            catch (Exception ex)
            {

            }
            return false;
        }

        /// <summary>
        /// 批量启用组织机构帐号
        /// </summary>
        public async Task<TasOrgUserMapEntity> GetById(Guid userId,int orgId)
        {
            var result = await _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity>().FirstAsync(it => it.UserId == userId && it.OrgId == orgId);
            return result;
        }

        /// <summary>
        /// 组织机构是否存在负责人
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExistLeader(int orgId)
        {
            return await _unitOfWork.QueryClient.Queryable<TasOrgUserMapEntity>().Where(it => it.OrgId == orgId && it.IsLeader == 1 ).CountAsync() > 0;
        }

        /// <summary>
        /// 获取某个大社下离c客最近的5个旅游顾问
        /// </summary>
        /// <param name="EmployeeIdList"></param>
        /// <returns></returns>
        public async Task<List<string>> GetNearestHxList(int orgId, decimal lng, decimal lat, int index)
        {
            try
            {
                var pageSize = 5;
                var startIndex = (index - 1) * pageSize;
                var parameters = new SugarParameter[] {
                    new SugarParameter("TopOrgId",orgId),
                    new SugarParameter("lng",lng),
                    new SugarParameter("lat",lat),
                    new SugarParameter("dist",100*1000),
                    new SugarParameter("startIndex",startIndex),
                    new SugarParameter("number",pageSize)
                };
                //var dt = await _unitOfWork.QueryClient.Ado.UseStoredProcedure().GetDataTableAsync("p_geo_tas_user_dist", parameters);
                var dt = await _unitOfWork.QueryClient.Ado.GetDataTableAsync("call p_geo_tas_user_dist(@TopOrgId,@lng,@lat,@dist,@startIndex,@number)", new { TopOrgId = orgId, lng = lng, lat = lat, dist = 100 * 1000, startIndex = startIndex, number = pageSize });

                if (dt == null || dt.Rows.Count == 0) return new List<string>();

                var nearList = _unitOfWork.QueryClient.Utilities.DataTableToList<TasUserBriefListDto>(dt);
                if (nearList?.Count > 0)
                {
                    return nearList.Select(it => it.HxUserName).ToList();
                }
                else
                {
                    return new List<string>();
                }

            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改WXOpenId
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateWXOpenId(TasOrgUserMapEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasOrgUserMapEntity>().SetColumns(it => new
            TasOrgUserMapEntity
            {
                WXOpenId = entity.WXOpenId
            })
                .Where(it => it.UserId == entity.UserId && it.OrgId == entity.OrgId)
                .ExecuteCommandAsync() > 0;
            return result;
            //var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new
            //{
            //    it.WXOpenId
            //}).ExecuteCommandAsync() > 0;
            //return result;
        }

        /// <summary>
        /// 根据orgId获取org的负责人
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<TasOrgUserMapEntity> GetOrgLeaderByOrgId(int orgId)
        {
            try
            {
                var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity>((u, ou) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                })
                //.Where(( u,ou) => u.IsDeleted == 0 && ou.IsLeader == 1 && (o.OrgLevel == (int)OrgLevel.Store|| o.OrgLevel == (int)OrgLevel.DirectlyUnder))
                .Where((u, ou) => u.IsDeleted == 0 && ou.IsLeader == 1 && ou.OrgId == orgId)
                .Select((u, ou) => ou).FirstAsync();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 修改是否需要编辑出团通知书
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orgId"></param>
        /// <param name="isEditDepartureNotice"></param>
        /// <returns></returns>
        public async Task<bool> UpdateIsEditDepartureNotice(Guid userId, int orgId, bool isEditDepartureNotice)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<TasOrgUserMapEntity>().SetColumns(it => new
            TasOrgUserMapEntity
            {
                IsEditDepartureNotice = isEditDepartureNotice
            })
                .Where(it => it.UserId == userId && it.OrgId == orgId)
                .ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 更新环信Id
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateHxUserName(TasOrgUserMapEntity entity)
        {
            var result = await _unitOfWork.ModifyClient.Updateable(entity)
                .UpdateColumns(it => new { it.HxUserName })
                .Where(it=>it.UserId==entity.UserId&&it.OrgId== entity.OrgId)
                .ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 根据orgIdList获取TasOrgUserMapList
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<TasOrgUserMapEntity>> GetListByOrgIdList(List<int> orgIdList)
        {
            try
            {
                if (orgIdList == null || orgIdList.Count == 0)
                {
                    return new List<TasOrgUserMapEntity>();
                }
                var result = await _unitOfWork.QueryClient.Queryable<TasUserEntity, TasOrgUserMapEntity>((u, ou) => new object[] {
                    JoinType.Inner, ou.UserId == u.Id,
                })
                .Where((u, ou) => u.IsDeleted == 0 && orgIdList.Contains( ou.OrgId))
                .Select((u, ou) => ou).ToListAsync();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }
        }
    }
}
